package com.baijiayun.liveuibase.toolbox.redpacket;

import android.annotation.SuppressLint;
import android.content.Context;
import androidx.core.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.baijiayun.livecore.context.LPException;
import com.baijiayun.livecore.models.LPRedPacketModel;
import com.baijiayun.livecore.utils.LPJsonUtils;
import com.baijiayun.livecore.utils.LPRxUtils;
import com.baijiayun.livecore.utils.ToastCompat;
import com.baijiayun.liveuibase.R;
import com.baijiayun.liveuibase.base.BaseTitleWindow;
import com.baijiayun.liveuibase.toolbox.redpacket.model.PublishRedPacketModel;
import com.baijiayun.liveuibase.utils.DisplayUtils;
import com.baijiayun.liveuibase.utils.ThemeDataUtil;
import com.baijiayun.liveuibase.utils.drawable.DrawableBuilder;
import com.baijiayun.liveuibase.utils.drawable.StateListDrawableBuilder;
import com.google.gson.JsonObject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class RedPacketPublishWindow extends BaseTitleWindow {
    private TextView tvNumSuggest;
    private EditText etNum;
    private TextView tvTime1;
    private TextView tvTime2;
    private TextView tvTime3;
    private TextView tvTime4;
    private TextView tvScoreSuggest;
    private EditText etScore;
    private TextView tvStart;

    /** 当前选中的时间 */
    private int nowSelectTime;
    /** 红包雨发布最大数量限制 */
    private int maxRedPacketLimit;

    private Disposable disposableOfPublish;

    public RedPacketPublishWindow(Context context) {
        super(context);
        setTitle(getString(R.string.base_red_packet_title));
    }

    @SuppressLint("StringFormatInvalid")
    @Override
    protected void onCreateContentView(Context context) {
        LayoutInflater.from(context).inflate(R.layout.uibase_window_red_packet_publish_layout, clContentContainer);
        tvNumSuggest = clContentContainer.findViewById(R.id.base_red_packet_num_suggest);
        etNum = clContentContainer.findViewById(R.id.base_red_packet_num_input);

        tvTime1 = clContentContainer.findViewById(R.id.base_red_packet_num_time_1);
        initTimeSelView(tvTime1, 5);
        tvTime2 = clContentContainer.findViewById(R.id.base_red_packet_num_time_2);
        initTimeSelView(tvTime2, 10);
        tvTime3 = clContentContainer.findViewById(R.id.base_red_packet_num_time_3);
        initTimeSelView(tvTime3, 15);
        tvTime4 = clContentContainer.findViewById(R.id.base_red_packet_num_time_4);
        initTimeSelView(tvTime4, 30);
        tvTime1.performClick();

        tvScoreSuggest = clContentContainer.findViewById(R.id.base_red_packet_score_suggest);
        etScore = clContentContainer.findViewById(R.id.base_red_packet_score_input);
        tvStart = clContentContainer.findViewById(R.id.base_red_packet_bt_start);

        tvStart.setBackground(ThemeDataUtil.getEnableProductBgWithCorner(context));
        tvStart.setTextColor(ThemeDataUtil.getColorEnableWhite2NegativeText(context));
        tvStart.setEnabled(false);

        clearInput();
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // do nothing
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // do nothing
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (tvStart != null) {
                    tvStart.setEnabled(checkInput());
                }
            }
        };
        etScore.addTextChangedListener(textWatcher);
        etNum.addTextChangedListener(textWatcher);
        tvStart.setOnClickListener(v -> {
            sendPublish();
        });

        initRoomData();
    }

    private void initRoomData() {
        if (routerListener.getLiveRoom() == null) {
            return;
        }
        maxRedPacketLimit = routerListener.getLiveRoom().getPartnerConfig().maxRedPacketCount;
        etNum.setHint(context.getString(R.string.base_red_packet_num_hint, String.valueOf(maxRedPacketLimit)));
        etScore.setHint(context.getString(R.string.base_red_packet_score_hint, String.valueOf(maxRedPacketLimit)));
        initSuggestViews();
    }

    private void sendPublish() {
        if (routerListener.getLiveRoom() == null || !checkInput()) {
            return;
        }
        DisplayUtils.hideKeyboard(etNum);
        LPRxUtils.dispose(disposableOfPublish);
        disposableOfPublish = routerListener.getLiveRoom().requestPublishRedPacket(
                Integer.parseInt(etNum.getText().toString()),
                Integer.parseInt(etScore.getText().toString()),
                nowSelectTime)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(lpShortResult -> {
                    PublishRedPacketModel publishRedPacketModel = LPJsonUtils.parseJsonObject(
                            (JsonObject) lpShortResult.data, PublishRedPacketModel.class);
                    if (publishRedPacketModel.status == 0 && routerListener != null) {
                        // 成功
                        routerListener.getLiveRoom().requestRedPacket(new LPRedPacketModel(
                                String.valueOf(publishRedPacketModel.packageId), nowSelectTime));
                        routerListener.onDismissRedPacketPublish();
                    }
                }, throwable -> {
                    if (throwable instanceof LPException) {
                        ToastCompat.showToastCenter(context, throwable.getMessage(), Toast.LENGTH_LONG);
                    }
                });
        compositeDisposable.add(disposableOfPublish);
        clearInput();
    }

    @Override
    protected void onCloseWindow() {
        if (routerListener != null) {
            routerListener.onDismissRedPacketPublish();
        }
    }

    private void initTimeSelView(TextView tvTime, int second) {
        tvTime.setBackground(new StateListDrawableBuilder()
                .selected(new DrawableBuilder()
                        .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color))
                        .cornerRadius(context.getResources().getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                        .build()
                ).normal(new DrawableBuilder()
                        .cornerRadius(context.getResources().getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                        .strokeColor(ContextCompat.getColor(context, R.color.base_bg_stroke))
                        .strokeWidth(DisplayUtils.dip2px(context, 1))
                        .build()
                ).build());
        tvTime.setTextColor(ThemeDataUtil.getColorSelectWhite2MainText(context));
        tvTime.setOnClickListener(v -> {
            nowSelectTime = second;
            tvTime1.setSelected(false);
            tvTime2.setSelected(false);
            tvTime3.setSelected(false);
            tvTime4.setSelected(false);
            tvTime.setSelected(true);
        });
    }

    /**
     * 初始化建议的红包数和学分数
     */
    private void initSuggestViews() {
        if (routerListener.getLiveRoom() == null) {
            return;
        }
        tvNumSuggest.setText(initSuggestString(5, 20, maxRedPacketLimit, R.string.base_red_packet_num_suggest));
        tvScoreSuggest.setText(initSuggestString(10, 40, maxRedPacketLimit, R.string.base_red_packet_score_suggest));
    }

    private String initSuggestString(int minRatio, int maxRatio, int limit, int prefixStringId) {
        if (routerListener == null || routerListener.getLiveRoom() == null) {
            return "";
        }
        int userCount = routerListener.getLiveRoom().getOnlineUserVM().getUserCount();
        int min = Math.min(userCount * minRatio, limit);
        int max = Math.min(userCount * maxRatio, limit);
        if (min == max) {
            return context.getString(prefixStringId, max);
        } else {
            return context.getString(prefixStringId, min + "~" + max);
        }
    }

    private boolean checkInput() {
        boolean validFlag = false;
        try {
            if (routerListener.getLiveRoom() == null) {
                return false;
            }
            int num = Integer.parseInt(etNum.getText().toString());
            int score = Integer.parseInt(etScore.getText().toString());
            validFlag = num > 0 && score >= num && num <= maxRedPacketLimit && score <= maxRedPacketLimit;
        } catch (Exception ignore) {
            // do nothing
        }
        return validFlag;
    }

    /**
     * 清空所有输入
     */
    private void clearInput() {
        etScore.setText("");
        etNum.setText("");
    }
}
